package bootstrap.liftweb

import _root_.net.liftweb.common._
import _root_.net.liftweb.util._
import _root_.net.liftweb.http._
import _root_.net.liftweb.sitemap._
import _root_.net.liftweb.sitemap.Loc._
import net.liftweb.mapper.{DB, ConnectionManager, Schemifier, DefaultConnectionIdentifier, ConnectionIdentifier}
import java.sql.{Connection, DriverManager}
import Helpers._
import net.liftweb.util._
import net.liftweb.http.LiftRules 
import java.util.Date

import com.salary.model._
/**
  * A class that's instantiated early and run.  It allows the application
  * to modify lift's environment
  */
class Boot {
  def boot {
    // where to search snippet
    LiftRules.addToPackages("com.salary")
	//database
    if (!DB.jndiJdbcConnAvailable_?) DB.defineConnectionManager(DefaultConnectionIdentifier, DBVendor)

    def schemeLogger (msg : => AnyRef) = {
      Logger(classOf[Boot]).info(msg)
    }
    Schemifier.schemify(true, schemeLogger _, User, Employee, SocialSecurity)

    // Build SiteMap
    //val entries = Menu(Loc("Home", List("index"), "Home")) :: Nil
    LiftRules.setSiteMap(SiteMap(MenuInfo.menu :_*))
  }

}
object MenuInfo {
  import Loc._
  val IfLoggedIn = If(() => User.currentUser.isDefined, "You must be logged in")
  val IfLoggedAsAdmin = If(() => User.currentUser.isDefined && (User.currentUser.open_!).operation >= 0, "You have no enough operation")
  val IfLoggedAsSalary = If(() => User.currentUser.isDefined && (User.currentUser.open_!).operation >= 2, "You have no enough operation")

  def menu: List[Menu] = 
    List[Menu](Menu("Home") / "index",
               Menu("Manage Employee") / "viewEmployee" >> IfLoggedAsSalary,
               Menu("edit Employee") / "editEmployee" >>Hidden >> IfLoggedAsSalary,
               Menu("Add Employee") / "addEmployee" >>Hidden >> IfLoggedAsSalary,
               Menu("Manage Users") / "viewUsers" >> IfLoggedIn,
               Menu("Edit User") / "editUser" >>Hidden >> IfLoggedIn,
               Menu("File Upload") / "fileUpload", 
               Menu("Manage SocialSecurity") / "SocialSecuritysView", 
               Menu("Add SocialSecurity") / "SocialSecuritysAdd" >>Hidden, 
               Menu("Edit SocialSecurity") / "SocialSecuritysEdit" >>Hidden, 
               Menu("Help") / "help" / "index") :::
    User.sitemap :::
	SocialSecurity.menus
  
}

object DBVendor extends ConnectionManager {
  def newConnection(name: ConnectionIdentifier): Box[Connection] = {
    try {
      /** Uncomment if you really want Derby
       * 
      Class.forName("org.apache.derby.jdbc.EmbeddedDriver")
      val dm = DriverManager.getConnection("jdbc:derby:pca_example;create=true")
      */

      Class.forName("org.h2.Driver")
      val dm = DriverManager.getConnection("jdbc:h2:pca_example")
      Full(dm)
    } catch {
      case e : Exception => e.printStackTrace; Empty
    }
  }
  def releaseConnection(conn: Connection) {conn.close}
}
